import { chain } from 'ramda';

import { Region } from '@/pages/management/system/region/type';

/**
 * Flatten an array containing a tree structure
 * @param {T[]} trees - An array containing a tree structure
 * @returns {T[]} - Flattened array
 */
export function flattenTrees<T extends { children?: T[] }>(trees: T[] = []): T[] {
  return chain((node) => {
    const children = node.children || [];
    return [node, ...flattenTrees(children)];
  }, trees);
}

export function listToTree(list: any[] = [], options = {}, data: any = null) {
  const { rootWhere, childsWhere, addChilds } = {
    rootWhere: (_: any, self: any) => {
      return (self.parent?.id || 0) === 0;
    },
    childsWhere: (parent: any, self: any) => {
      return parent.id === self.parent?.id;
    },
    addChilds: (parent: any, childList: any[]) => {
      if (childList?.length > 0) {
        parent.children = childList;
      }
    },
    ...(options || {}),
  };
  let tree = [] as any;
  // 空列表
  if (!(list?.length > 0)) {
    return tree;
  }
  // 顶级
  const rootList = list.filter((item: any) => rootWhere && rootWhere(data, item));
  if (!(rootList?.length > 0)) {
    return tree;
  }
  tree = tree.concat(rootList);
  // 子级
  tree.forEach((root: any) => {
    const rootChildList = list.filter((item: any) => childsWhere && childsWhere(root, item));
    if (!(rootChildList?.length > 0)) {
      return;
    }
    rootChildList.forEach((item: any) => {
      const childList = listToTree(list, { rootWhere: childsWhere, childsWhere, addChilds }, item);
      addChilds && addChilds(item, childList);
    });
    addChilds && addChilds(root, rootChildList);
    // 判断叶子节点,暂时没有作用
    if (!root.children || root.children.length === 0) {
      root.isLeaf = true;
    }
  });

  return tree;
}
